<?php

class DepartmentController extends ControllerBase
{

    public function indexAction()
    {
        $this->view->departments = OaDepartments::getAll();
    }

    public function saveAction()
    {
        $request = $this->request;

        if ($request->isPost()) {
            $dept_id = $request->getPost('dept_id', 'int');
            $departments = $request->getPost('department');

            if ($dept_id) {
                $model = OaDepartments::findFirst('dept_id=' . $dept_id);
            } else {
                $model = new OaDepartments;
            }

            $data = array(
                'parent_id'  => $request->getPost('parent_id', 'int'),
                'department' => $departments['en-us'],
                'sort_order' => $request->getPost('sort_order', 'int'),
            );

            if ($model->save($data)) {
                // 写入其它语言部门名称
                foreach ($departments as $lang => $text) {
                    OaTranslates::write('department', $model->dept_id, $text, $lang);
                }

                return $this->ajax->success();
            }

            return $this->ajax->error($model->getMessage());
        }
    }

    public function modalAction($dept_id = 0)
    {
        $dept = array();
        if ($dept_id) {
            $dept = OaDepartments::getOne($dept_id);
            foreach ($this->langs as $lang => $t) {
                $dept['department.' . $lang] = db_translate($dept['department'], 'department', $dept['dept_id'], $lang);
            }
        }

        $this->view->department = $dept;
        $this->view->departments = OaDepartments::getAll();
    }

    public function deleteAction($dept_id)
    {
        if (! $model = OaDepartments::findFirst('dept_id=' . $dept_id)) {
            return $this->ajax->error(__('The record not found'));
        }

        if ($model->delete()) {
            return $this->ajax->success();
        }

        return $this->ajax->error($model->getMessage());
    }

}
